<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <!-- 搜索操作 -->
      <template #header>
        <div class="card-header">
          <span>筛选条件</span>
          <el-button
            class="collapse-btn"
            type="text"
            @click="toggleSearch"
            :icon="showSearch ? 'ArrowDownBold' : 'ArrowUpBold'"
          >
            {{ showSearch ? "收起" : "展开" }}
          </el-button>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form
        :model="queryParams"
        ref="goodsRef"
        :inline="true"
        v-show="showSearch"
        label-width="110px"
      >
        <!-- 搜索条件行 -->
        <el-row :gutter="25" class="mb15">
          <el-col :span="6">
            <el-form-item label="商品分类" prop="categoryId">
              <el-tree-select
                v-model="queryParams.categoryId"
                :data="categoryOptions"
                :props="{
                  value: 'categoryId',
                  label: 'categoryName',
                  children: 'children',
                }"
                value-key="categoryId"
                placeholder="请选择商品分类"
                clearable
                check-strictly
                @change="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input
                v-model="queryParams.goodsName"
                placeholder="请输入商品名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品编码(SKU)" prop="goodsCode">
              <el-input
                v-model="queryParams.goodsCode"
                placeholder="请输入商品编码(SKU)"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标记信息" prop="tags">
              <el-select
                v-model="queryParams.tags"
                placeholder="请选择标记信息"
                clearable
              >
                <el-option
                  v-for="dict in tags"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择状态"
                clearable
              >
                <el-option
                  v-for="dict in wdm_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 搜索按钮行 - 右对齐 -->
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8 mt-15">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:goods:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi:goods:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi:goods:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi:goods:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="goodsList"
      @selection-change="handleSelectionChange"
      border
      stripe
      class="mt-10"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        width="60px"
        align="center"
        prop="goodsId"
      />

      <el-table-column
        label="商品名称"
        align="center"
        prop="goodsName"
        show-overflow-tooltip="true"
      />
      <!-- <el-table-column label="商品编码" align="center" prop="goodsCode" /> -->
      <el-table-column
        label="商品图片"
        align="center"
        prop="imgUrl"
        width="100"
      >
        <template #default="scope">
          <image-preview :src="scope.row.imgUrl" :width="50" :height="50" />
        </template>
      </el-table-column>

      <el-table-column label="商品价格" align="center" prop="price">
        <template #default="scope">
          <el-tag> {{ scope.row.price }}￥ </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="售价" align="center" prop="salePrice">
        <template #default="scope">
          <el-tag> {{ scope.row.salePrice }}￥ </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="折扣率" align="center" prop="discountValue">
        <template #default="scope">
          <el-tag> {{ scope.row.discountValue }}折 </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="总库存" align="center" prop="totalStock" />
      <!-- <el-table-column label="销量" align="center" prop="salesVolume" /> -->
      <el-table-column label="标记信息" align="center" prop="tags">
        <template #default="scope">
          <dict-tag :options="tags" :value="scope.row.tags" />
        </template>
      </el-table-column>
      <el-table-column
        label="商品描述"
        align="center"
        width="200px"
        prop="description"
        show-overflow-tooltip
      />

      <!-- <el-table-column label="备注信息" align="center" prop="remark" /> -->

      <el-table-column
        label="创建时间"
        align="center"
        width="180px"
        prop="createTime"
      />

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200px"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="getGoodsInfo(scope.row)"
            v-hasPermi="['ruoyi:goods:list']"
            >查看详情</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:goods:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:goods:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      class="mt-15"
    />
    <!-- 添加或修改商品信息对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="720px"
      append-to-body
    >
      <el-collapse v-model="activeCollapse">
        <!-- 基本信息组 -->
        <el-collapse-item name="basic" title="基本信息">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品分类" prop="categoryId">
                <el-tree-select
                  v-model="form.categoryId"
                  style="width: 100%"
                  :data="categoryOptions"
                  :props="{
                    value: 'categoryId',
                    label: 'categoryName',
                    children: 'children',
                  }"
                  value-key="categoryId"
                  placeholder="请选择分类"
                  check-strictly
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品名称" prop="goodsName">
                <el-input
                  v-model="form.goodsName"
                  placeholder="请输入商品名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品编码(SKU)" prop="goodsCode">
                <el-input
                  v-model="form.goodsCode"
                  placeholder="请输入商品编码(SKU)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in wdm_status"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 价格与库存组 -->
        <el-collapse-item name="price" title="价格与库存">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="商品价格"
                prop="price"
                class="price-highlight"
              >
                <el-input-number
                  v-model="form.price"
                  :min="0"
                  :precision="2"
                  :step="1.0"
                  controls-position="right"
                  placeholder="0.00"
                  style="width: 100%"
                >
                  <template #prefix>
                    <span style="color: #f56c6c; font-weight: bold">¥</span>
                  </template>
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="折扣率" prop="discountValue">
                <el-input-number
                  v-model="form.discountValue"
                  :min="0"
                  :max="10"
                  :precision="1"
                  :step="0.1"
                  controls-position="right"
                  placeholder="请输入折扣(0-10)"
                  style="width: 100%"
                >
                  <template #suffix>折</template>
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="实际售价" class="sale-price-field">
                <el-input
                  v-model="calculatedSalePrice"
                  disabled
                  placeholder="根据价格和折扣自动计算"
                >
                  <template #prefix>
                    <span style="color: #f56c6c; font-weight: bold">¥</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总库存" prop="totalStock">
                <el-input-number
                  v-model="form.totalStock"
                  :min="0"
                  :precision="0"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销量" prop="salesVolume">
                <el-input-number
                  v-model="form.salesVolume"
                  :min="0"
                  :precision="0"
                  controls-position="right"
                  style="width: 100%"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 详细信息组 -->
        <el-collapse-item name="detail" title="详细信息">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="商品主图" prop="imgUrl">
                <image-upload v-model="form.imgUrl" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <!-- <el-form-item label="标记信息" prop="tags">
                <el-input v-model="form.tags" placeholder="请输入标记信息" />
              </el-form-item> -->
              <el-form-item label="标记信息" prop="tags">
                <el-select v-model="form.tags" placeholder="请选择标记信息">
                  <el-option
                    v-for="dict in tags"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商家ID" prop="merchantId">
                <el-input
                  v-model="form.merchantId"
                  placeholder="请输入商家ID"
                />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="商品详情内容">
                <editor v-model="form.detailContent" :min-height="192" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="图文详情图片" prop="detailImages">
                <image-upload
                  v-model="form.detailImages"
                  :multiple="true"
                  :is="multiple"
                />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="订购须知">
                <el-button
                  type="primary"
                  icon="Plus"
                  @click="addPurchaseNote"
                  size="small"
                  >添加须知</el-button
                >
                <el-table
                  :data="purchaseNotesList"
                  border
                  style="margin-top: 10px"
                >
                  <el-table-column label="标题" width="150">
                    <template #default="scope">
                      <el-input
                        v-model="scope.row.title"
                        placeholder="请输入标题"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="内容">
                    <template #default="scope">
                      <el-input
                        v-model="scope.row.content"
                        type="textarea"
                        :rows="2"
                        :autosize="{ minRows: 2, maxRows: 6 }"
                        placeholder="请输入内容"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="80">
                    <template #default="scope">
                      <el-button
                        link
                        type="danger"
                        icon="Delete"
                        @click="removePurchaseNote(scope.$index)"
                      />
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="商品规格">
                <el-tabs v-model="specActiveTab">
                  <el-tab-pane label="规格设置" name="specs">
                    <el-button
                      type="primary"
                      icon="Plus"
                      @click="addSpec"
                      size="small"
                      >添加规格</el-button
                    >
                    <el-table :data="specList" border style="margin-top: 10px">
                      <el-table-column label="规格名称" width="150">
                        <template #default="scope">
                          <el-input
                            v-model="scope.row.name"
                            placeholder="例如：规格、口味"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="可选值" width="300">
                        <template #default="scope">
                          <el-tag
                            v-for="(value, index) in scope.row.values"
                            :key="index"
                            closable
                            @close="removeSpecValue(scope.$index, index)"
                            style="margin-right: 5px"
                          >
                            {{ value }}
                          </el-tag>
                          <el-input
                            v-if="scope.row.inputVisible"
                            ref="specInputRef"
                            v-model="scope.row.inputValue"
                            class="input-new-tag"
                            size="small"
                            @keyup.enter="handleInputConfirm(scope.$index)"
                            @blur="handleInputConfirm(scope.$index)"
                          />
                          <el-button
                            v-else
                            class="button-new-tag"
                            size="small"
                            @click="showInput(scope.$index)"
                          >
                            + 添加
                          </el-button>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="80">
                        <template #default="scope">
                          <el-button
                            link
                            type="danger"
                            icon="Delete"
                            @click="removeSpec(scope.$index)"
                          />
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-tab-pane>
                  <el-tab-pane label="SKU设置" name="skus">
                    <el-table :data="skuList" border style="margin-top: 10px">
                      <el-table-column
                        v-for="(spec, index) in specList"
                        :key="index"
                        :label="spec.name"
                        width="120"
                      >
                        <template #default="scope">
                          {{ scope.row.specs[index] }}
                        </template>
                      </el-table-column>
                      <el-table-column label="价格" width="120">
                        <template #default="scope">
                          <el-input-number
                            v-model="scope.row.price"
                            :min="0"
                            :precision="2"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="库存" width="120">
                        <template #default="scope">
                          <el-input-number v-model="scope.row.stock" :min="0" />
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-tab-pane>
                </el-tabs>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="商品描述" prop="description">
                <el-input
                  v-model="form.description"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注信息" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>

      <template #footer>
        <div class="dialog-footer" style="text-align: center; margin-top: 15px">
          <el-button v-if="!isViewMode.value" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">{{
            isViewMode.value ? "关 闭" : "取 消"
          }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
} from "@/api/ruoyi/goods";
import { listCategory } from "@/api/ruoyi/category";

// import { loadAllParams } from "@/api/page";

import { ref } from "vue";

const { proxy } = getCurrentInstance();
const { wdm_status, tags, del_flag } = proxy.useDict(
  "wdm_status",
  "tags",
  "del_flag"
);

const goodsList = ref([]);

const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: null,
    goodsName: null,
    goodsCode: null,
    imgUrl: null,
    description: null,
    price: null,
    salePrice: null,
    discountValue: null,
    totalStock: null,
    salesVolume: null,
    status: null,
    version: null,
    tags: null,
    merchantId: null,
    detailContent: null,
    detailImages: null,
    purchaseNotes: null,
    specifications: null,
  },
  rules: {
    categoryId: [
      { required: true, message: "商品分类ID不能为空", trigger: "blur" },
    ],
    goodsName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" },
    ],
    price: [{ required: true, message: "商品价格不能为空", trigger: "blur" }],
    discountValue: [
      { required: true, message: "折扣率不能为空", trigger: "blur" },
      {
        type: "number",
        min: 0,
        max: 10,
        message: "折扣率必须在0-10之间",
        trigger: "blur",
      },
    ],
    goodsCode: [
      { required: true, message: "商品编码(SKU)不能为空", trigger: "blur" },
    ],
    totalStock: [
      { required: true, message: "总库存不能为空", trigger: "blur" },
    ],
  },
  isViewMode: false, // 是否查看模式
});

const { queryParams, form, rules, isViewMode } = toRefs(data);

// 订购须知相关
const purchaseNotesList = ref([]);

// 规格相关
const specActiveTab = ref("specs");
const specList = ref([]);
const skuList = ref([]);

// 初始化数据
watch(
  form,
  (newVal) => {
    // 初始化订购须知
    if (newVal.purchaseNotes) {
      try {
        purchaseNotesList.value = JSON.parse(newVal.purchaseNotes);
      } catch (e) {
        purchaseNotesList.value = [];
      }
    } else {
      purchaseNotesList.value = [];
    }

    // 初始化规格
    if (newVal.specifications) {
      try {
        const specsData = JSON.parse(newVal.specifications);
        specList.value = specsData.specs || [];
        skuList.value = specsData.skus || [];
      } catch (e) {
        specList.value = [];
        skuList.value = [];
      }
    } else {
      specList.value = [];
      skuList.value = [];
    }
  },
  { immediate: true }
);

// 订购须知方法
function addPurchaseNote() {
  purchaseNotesList.value.push({ title: "", content: "" });
}

function removePurchaseNote(index) {
  purchaseNotesList.value.splice(index, 1);
}

// 规格方法
function addSpec() {
  specList.value.push({
    name: "",
    values: [],
    inputVisible: false,
    inputValue: "",
  });
}

function showInput(index) {
  specList.value[index].inputVisible = true;
  nextTick(() => {
    if (specInputRef.value && specInputRef.value[index]) {
      specInputRef.value[index].focus();
    }
  });
}

function handleInputConfirm(index) {
  const inputValue = specList.value[index].inputValue;
  if (inputValue) {
    specList.value[index].values.push(inputValue);
  }
  specList.value[index].inputVisible = false;
  specList.value[index].inputValue = "";
}

function removeSpecValue(specIndex, valueIndex) {
  specList.value[specIndex].values.splice(valueIndex, 1);
}

function removeSpec(index) {
  specList.value.splice(index, 1);
  // 重新生成SKU
  generateSkus();
}

// 提交前处理数据
function beforeSubmit() {
  // 处理订购须知 - 清理空值
  const validPurchaseNotes = purchaseNotesList.value.filter(
    (item) => item.title && item.content
  );
  form.value.purchaseNotes = JSON.stringify(validPurchaseNotes);

  // 处理规格 - 清理UI属性
  const cleanSpecs = specList.value
    .map((spec) => ({
      name: spec.name,
      values: spec.values.filter((v) => v.trim() !== ""),
    }))
    .filter((spec) => spec.name && spec.values.length > 0);

  const cleanSkus = skuList.value
    .map((sku) => ({
      specs: sku.specs,
      price: sku.price,
      stock: sku.stock,
    }))
    .filter((sku) => sku.price > 0 && sku.stock >= 0);

  form.value.specifications = JSON.stringify({
    specs: cleanSpecs,
    skus: cleanSkus,
  });
}

// 折叠面板默认展开项
const activeCollapse = ref(["basic", "price", "detail"]);

// 添加查看模式下的样式处理
watch(isViewMode, (newValue) => {
  if (newValue) {
    nextTick(() => {
      const inputs = document.querySelectorAll(
        ".el-input, .el-select, .el-tree-select, .el-input-number"
      );
      inputs.forEach((input) => {
        input.classList.add("is-disabled");
      });
    });
  }
});

// 新增：搜索区域折叠/展开
function toggleSearch() {
  showSearch.value = !showSearch.value;
}

// 在<script setup>中添加
const categoryMap = computed(() => {
  const map = {};
  const buildMap = (categories) => {
    for (const category of categories) {
      map[category.categoryId] = category.categoryName;
      if (category.children && category.children.length) {
        buildMap(category.children);
      }
    }
  };

  // 从顶级节点的子节点开始构建映射
  if (categoryOptions.value.length > 0 && categoryOptions.value[0].children) {
    buildMap(categoryOptions.value[0].children);
  }
  return map;
});

// 计算属性 - 实际售价
const calculatedSalePrice = computed(() => {
  if (form.value.price && form.value.discountValue) {
    return ((form.value.price * form.value.discountValue) / 10).toFixed(2);
  }
  return "0.00";
});

// 监听价格和折扣率变化，自动更新表单中的salePrice字段
watch([() => form.value.price, () => form.value.discountValue], () => {
  if (form.value.price && form.value.discountValue) {
    form.value.salePrice = (
      (form.value.price * form.value.discountValue) /
      10
    ).toFixed(2);
  } else {
    form.value.salePrice = null;
  }
});

// 商品分类信息下拉框
const categoryOptions = ref([]);

// 获取商品分类信息树列表
function getTreeselect() {
  listCategory().then((response) => {
    categoryOptions.value = [];
    // 构建顶级节点
    const data = {
      categoryId: 0,
      categoryName: "顶级节点",
      children: [],
    };
    // 将扁平数据转为树形结构
    data.children = proxy.handleTree(response.data, "categoryId", "parentId");
    categoryOptions.value.push(data);
  });
}

/** 查询商品信息列表 */
function getList() {
  loading.value = true;
  listGoods(queryParams.value).then((response) => {
    // goodsList.value = response.rows;
    // 过滤已删除数据（假设 delFlag 字段标识删除状态）
    goodsList.value = response.rows.filter((item) => item.delFlag !== "2");
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    goodsId: null,
    categoryId: null,
    goodsName: null,
    goodsCode: null,
    imgUrl: null,
    description: null,
    price: null,
    salePrice: null,
    discountValue: 10, // 默认无折扣
    totalStock: null,
    salesVolume: null,
    status: "0", // 默认状态
    delFlag: null,
    version: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
    tags: null,
    merchantId: null,
    detailContent: null,
    detailImages: null,
    purchaseNotes: null,
    specifications: null,
  };
  proxy.resetForm("goodsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.goodsId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getTreeselect(); // 加载树形数据
  open.value = true;
  title.value = "添加商品信息";
}

/** 查看详情按钮操作 */
function getGoodsInfo(row) {
  reset();
  const _goodsId = row.goodsId;
  getGoods(_goodsId).then((response) => {
    form.value = response.data;
    isViewMode.value = true;
    open.value = true;
    title.value = "商品详情";

    // 查看模式下禁用所有输入
    if (isViewMode.value) {
      const formItems = document.querySelectorAll(".el-form-item");
      formItems.forEach((item) => {
        const input = item.querySelector(
          "input, .el-input, .el-select, .el-tree-select"
        );
        if (input) {
          input.setAttribute("disabled", "disabled");
        }
      });
    }
  });
}
// function getGoodsInfo(row) {
//   // 查询商品信息
//   reset();
//   const _goodsId = row.goodsId;
//   getGoods(_goodsId).then((response) => {
//     form.value = response.data;
//   });
// }

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect(); // 加载树形数据
  const _goodsId = row.goodsId || ids.value;
  getGoods(_goodsId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商品信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodsRef"].validate((valid) => {
    if (valid) {
      beforeSubmit(); // 处理特殊字段
      if (form.value.goodsId != null) {
        updateGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
// function submitForm() {
//   proxy.$refs["goodsRef"].validate((valid) => {
//     if (valid) {
//       if (form.value.goodsId != null) {
//         updateGoods(form.value).then((response) => {
//           proxy.$modal.msgSuccess("修改成功");
//           open.value = false;
//           getList();
//         });
//       } else {
//         addGoods(form.value).then((response) => {
//           proxy.$modal.msgSuccess("新增成功");
//           open.value = false;
//           getList();
//         });
//       }
//     }
//   });
// }

/** 删除按钮操作 */
function handleDelete(row) {
  const _goodsIds = row.goodsId || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品信息编号为"' + _goodsIds + '"的数据项？')
    .then(function () {
      return delGoods(_goodsIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/goods/export",
    {
      ...queryParams.value,
    },
    `goods_${new Date().getTime()}.xlsx`
  );
}

getList();
//  获取分类列表
getTreeselect();
</script>


<style scoped>
/* 自适应对话框样式 */
:deep(.auto-resize-dialog) {
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

:deep(.auto-resize-dialog .el-dialog__body) {
  overflow: hidden;
  flex: 1;
  min-height: 200px;
}

:deep(.auto-resize-dialog .el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

/* 表格内文本域样式优化 */
:deep(.purchase-notes-table .el-textarea__inner) {
  min-height: 42px !important;
  transition: height 0.3s;
}

/* 对话框滚动时的阴影效果 */
:deep(.auto-resize-dialog.has-scroll) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
}
/* 搜索卡片样式 */
.search-card {
  /* margin-bottom: 16px; */
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #303133;
}

.collapse-btn {
  padding: 0;
  font-size: 14px;
  color: #606266;
}
/* 增加区块间距 */
.mt-10 {
  margin-top: 10px;
}

.mt-15 {
  margin-top: 15px;
}

.mb15 {
  margin-bottom: 15px;
}

/* 卡片样式优化 */
.box-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
}

.box-card .card-header {
  font-weight: 600;
  font-size: 18px;
  color: #1890ff;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.box-card .card-content {
  padding: 15px 10px;
}

/* 表单元素间距统一 */
.el-form-item {
  margin-bottom: 22px;
}

/* 价格字段突出显示 */
.price-highlight :deep(.el-input__inner) {
  border-color: #f56c6c;
  font-weight: bold;
  transition: all 0.3s;
}

.price-highlight :deep(.el-input__inner):focus {
  border-color: #f56c6c;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
}

/* 实际售价特殊背景 */
.sale-price-field :deep(.el-input__inner) {
  background-color: #fffbe6;
  border-color: #faad14;
  font-weight: bold;
}

/* 对话框内边距调整 */
:deep(.el-dialog__body) {
  padding: 20px 25px;
}

/* 表格斑马条纹优化 */
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: #fafafa;
}

.box-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.price-highlight :deep(.el-input__inner) {
  border-color: #f56c6c;
  font-weight: bold;
}

.el-form-item {
  margin-bottom: 18px;
}

/* 折叠面板统一间距 */
.el-collapse-item__content {
  padding-bottom: 10px;
}

/* 表单元素间距统一 */
.el-form-item {
  margin-bottom: 18px;
}

/* 价格字段突出显示 */
.price-highlight :deep(.el-input__inner) {
  border-color: #f56c6c;
  font-weight: bold;
  transition: all 0.3s;
}

.price-highlight :deep(.el-input__inner):focus {
  border-color: #f56c6c;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
}

/* 实际售价特殊背景 */
.sale-price-field :deep(.el-input__inner) {
  background-color: #fffbe6;
  border-color: #faad14;
  font-weight: bold;
}
</style>
